import echarts from 'echarts'
import Vue from 'vue'
import throttle from 'lodash/throttle'

export const version = '0.0.1'
const compatible = /^2\./.test(Vue.version)
if (!compatible) {
  Vue.util.warn(
    'vue echarts resize directive ' +
      version +
      ' only supports Vue 2.x, and does not support Vue ' +
      Vue.version
  )
}
const HANDLER = '_vue_echarts_resize_handler'

function unbind (el) {
  window.removeEventListener('resize', el[HANDLER])
  delete el[HANDLER]
}
function bind (el) {
  unbind(el)
  const resizeFn = () => {
    const chart = echarts.getInstanceByDom(el)
    if (!chart) {
      return
    }
    chart.resize()
  }
  el[HANDLER] = throttle(resizeFn, 1500)
  window.addEventListener('resize', el[HANDLER])
}
const directive = {
  bind,
  unbind
}
export default directive
